<?php
namespace App\Http\Controllers;

use App\Models\Message;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;

class MessageController extends Controller {
    
    /**
     * 后台：分页+搜索获取留言（可按 status 过滤）
     * 返回格式与标签列表一致
     */
    public function index(Request $request): JsonResponse {
        $query = Message::with(['user', 'children.user']);
        if ($request->has('status')) {
            $query->where('status', $request->input('status'));
        }
        // 搜索功能
        if ($search = $request->input('search')) {
            $query->where(function($q) use ($search) {
                $q->where('content', 'like', "%$search%")
                  ->orWhere('guest_name', 'like', "%$search%")
                  ->orWhere('guest_email', 'like', "%$search%")
                  ->orWhere('guest_phone', 'like', "%$search%")
                  ;
            });
        }
        $perPage = $request->input('per_page', 10);
        $messages = $query->orderBy('created_at', 'desc')->paginate($perPage);
        return response()->json([
            'data' => $messages->items(),
            'meta' => [
                'current_page' => $messages->currentPage(),
                'per_page' => $messages->perPage(),
                'total' => $messages->total(),
                'last_page' => $messages->lastPage(),
                'from' => $messages->firstItem(),
                'to' => $messages->lastItem(),
            ],
            'links' => [
                'first' => $messages->url(1),
                'last' => $messages->url($messages->lastPage()),
                'prev' => $messages->previousPageUrl(),
                'next' => $messages->nextPageUrl(),
            ],
            'message' => '成功获取留言列表',
        ], 200);
    }

    
    /**
     * 后台：审核留言
     */
    public function updateStatus(Request $request, Message $message): JsonResponse {
        $validated = $request->validate([
            'status' => 'required|in:pending,approved,rejected',
        ]);
        $message->status = $validated['status'];
        $message->save();
        return response()->json([
            'data' => $message,
            'message' => '留言状态已更新',
        ]);
    }

    /**
     * 回复留言
     */
    public function reply(Request $request, Message $message): JsonResponse
    {
        $validated = $request->validate([
            'content' => 'required|string|max:500',
        ]);
        $reply = Message::create([
            'guest_name' => '管理员',
            'content' => $validated['content'],
            'parent_id' => $message->id,
            'user_id' => auth()->id(),
        ]);
        $reply->load('user');
        return response()->json([
            'data' => $reply,
            'message' => '回复成功',
        ], 201);
    }

    /**
     * 删除留言
     */
    public function destroy(Message $message): JsonResponse
    {
        $message->children()->delete();
        $message->delete();
        return response()->json([
            'message' => '留言删除成功',
        ], 200);
    }

    /**
     * 批量删除留言
     * DELETE /messages
     */
    public function destroyBatch(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'ids' => 'required|array',
            'ids.*' => 'integer|exists:messages,id',
        ]);
        foreach ($validated['ids'] as $id) {
            $message = Message::find($id);
            if ($message) {
                $message->children()->delete();
                $message->delete();
            }
        }
        return response()->json([
            'message' => '批量删除成功',
        ], 200);
    }


    /**
     * 前台：提交留言（status 默认 pending）
     */
    public function publicStore(Request $request): JsonResponse {
        $validated = $request->validate([
            'guest_name' => 'required|string|max:50',
            'guest_email' => 'nullable|email|max:255',
            'guest_phone' => 'nullable|string|max:20',
            'content' => 'required|string|max:500',
            'parent_id' => 'nullable|exists:messages,id',
        ]);
        $message = Message::create([
            'guest_name' => $validated['guest_name'],
            'guest_email' => $validated['guest_email'] ?? null,
            'guest_phone' => $validated['guest_phone'] ?? null,
            'content' => $validated['content'],
            'parent_id' => $validated['parent_id'] ?? null,
            'user_id' => null,
            'status' => 'pending',
        ]);
        return response()->json([
            'data' => $message,
            'message' => '留言成功，等待审核',
        ], 201);
    }

    /**
     * 前台：获取已审核留言（带回复）
     */
    public function publicIndex(): JsonResponse {
        $messages = Message::whereNull('parent_id')
            ->where('status', 'approved')
            ->with(['children' => function($q) {
                $q->where('status', 'approved')->with('user');
            }, 'user'])
            ->orderBy('created_at', 'desc')
            ->get();
        return response()->json([
            'data' => $messages,
            'message' => $messages->isEmpty() ? '暂无留言' : '获取留言成功',
        ], 200);
    }
}
